package com.wcy.filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Set;

/**
 * <p>Title:JwtCheckFilter.java</p >
 * <p>Description: </p >
 * <p>Copyright: 公共服务与应急管理战略业务本部 Copyright(c)2020</p >
 * <p>Date:2021/9/13 17:07</p >
 *
 * @author wcy (wangchaoyanga@mail.taiji.com.cn)
 * @version 1.0
 */
@Component
public class JwtCheckFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${no.require.urls:/admin/login}")
    private Set<String> noRequireTokenUrls;
    /**
     * 过滤器拦截到用户请求后的处理
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1 : 该接口是否需要token才能访问
        if(!isRequireToken(exchange)){
            return chain.filter(exchange); // 不需要token 直接放行
        }
        // 2 : 如果需要token才能访问 取出用户的token
        String token=getUserToken(exchange);
        // 3 ： 判断用户token是否有效
        if(StringUtils.isEmpty(token)){
            return buildNoAuthResult(exchange);
        }
        Boolean hasKey = redisTemplate.hasKey(token);
        if(hasKey != null && hasKey){
            return chain.filter(exchange); // token有效 直接放行
        }
        return buildNoAuthResult(exchange);
    }

    /**
     * 给用户响应一个没有token的错误
     * @param exchange
     * @return
     */
    private Mono<Void> buildNoAuthResult(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set("Content-Type","application/json;charset=UTF-8");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error","NO Authorization");
        jsonObject.put("errorMsg","Toke is NULL");
        DataBuffer buffer = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Flux.just(buffer));
    }

    /**
     * 从请求头里获取用户token
     * @param exchange
     * @return
     */
    private String getUserToken(ServerWebExchange exchange) {
        String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        return token == null ? null : token.replace("bearer ","");
    }

    /**
     * 判断该接口是否需要token才能访问
     * @param exchange
     * @return
     */
    private boolean isRequireToken(ServerWebExchange exchange) {
        String path = exchange.getRequest().getURI().getPath();
        return !noRequireTokenUrls.contains(path);
    }

    /**
     * 拦截器顺序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
